<template>
  <input v-if="isUploadInput" v-show="false" :id="elementId" type="file" @change="onChange" :multiple="multiple"
         :accept="accept"/>
</template>

<script>
  import {uploadOssMixin} from '../mixins/request'
  import {uid} from 'quasar'

  export default {
    name: 'aUpload',
    mixins: [uploadOssMixin],
    props: {
      target: {
        type: String,
        required: false,
        default: 'server'
      },
      accept: {
        type: String,
        required: false,
        default: 'image/png, image/gif, image/jpeg'
      },
      maxSize: {
        type: Number,
        required: false,
        default: 16
      },
      multiple: {
        type: Boolean,
        required: false,
        default: false
      }
    },
    data() {
      return {
        isUploadInput: true,
        elementId: 'upload-input' + uid()
      }
    },
    computed: {},
    watch: {},
    methods: {
      openFileDialog() {
        document.getElementById(this.elementId).click()
      },
      async onChange(event) {
        this.$emit('startLoading')
        const files = event.target.files
        let result

        if (this.maxSize){
          for (let i =0; i<files.length;i++) {
            const file = files[i]
            if (file.size > this.maxSize * 1024 * 1024) {
              this.notify('error', `上传图片不能超过${maxSize}MB`)
              this.$emit('stopLoading')
              return
            }
          }
        }

        if (this.multiple){
          result = []

          for (let i =0; i<files.length;i++) {
            const {status, data} = await this.upload(files[i])

            if (status === 200){
              result.push(data)
            }else{
              this.notify('error', '上传图片失败，请稍后重试！')
              break
            }
          }
        }else{
          const {status, data} = await this.upload(files[0])
          if (status === 200){
            result = data
          }else{
            this.notify('error', '上传图片失败，请稍后重试！')
          }
        }

        if (result){
          this.$emit('uploaded', result)
        }
        this.$emit('stopLoading')
      },
      async upload(file) {
        let maxSize = this.maxSize

        this.isUploadInput = false

        setTimeout(() => {
          this.isUploadInput = true
        }, 100)

        if (maxSize && file.size > maxSize * 1024 * 1024) {
          this.notify('error', `上传图片不能超过${maxSize}MB`)
          return {status: 400}
        }
        let result
        if (this.target) {
          result = await this.uploadServerFile(file)
        } else {
          const dataUrl = await this.readFile(file)
          const size = await this.getImageSize(dataUrl)
          result = await this.uploadOssFile(file, 'forum', size)
        }

        return result
      }
    }
  }
</script>

<style lang="stylus">
</style>
